package controllers

import (
	"errors"
	"github.com/gogf/gf/os/glog"
	"mdblog/models"
	"mdblog/models/auth"
)

const (
	AdminApiPrefix      = "/api/admin"
	AdminApiLoginPrefix = AdminApiPrefix + "/login"
)

type AdminApiController struct {
	AjaxController
}

func (o *AdminApiController) Prepare() {
	if o.Ctx.Request.RequestURI != AdminApiLoginPrefix {
		if u := o.GetSession("user"); u == nil {
			o.ErrorResponse(errors.New("need login"))
			return
		}
	}
	o.Data["Configs"], _ = models.GetAllConfigs()
}

func (o *AdminApiController) Logout() {
	o.DestroySession()
	o.MessageResponse("ok")
}

func (o *AdminApiController) UserQuery() {
	request := UserQueryPaginator{}
	if err := o.LoadRequest(&request); err != nil {
		o.ErrorResponse(err)
	} else {
		users, total, err := request.Do()
		if err != nil {
			o.ErrorResponse(err)
		} else {
			o.DataTableResponse(users, total, "ok")
		}
	}
}

func (o *AdminApiController) AccountCreate() {
	request := UserCreateRequest{}
	if err := o.LoadRequest(&request); err != nil {
		o.ErrorResponse(err)
	} else {
		err := request.Do()
		if err != nil {
			o.ErrorResponse(err)
		} else {
			o.MessageResponse("ok")
		}
	}
}

func (o *AdminApiController) ChangePassword() {
	request := UserChangePassRequest{}
	if err := o.LoadRequest(&request); err != nil {
		o.ErrorResponse(err)
	} else {
		err := request.Do()
		if err != nil {
			text := ""
			switch err {
			case auth.PasswordError:
				text = "密码错误"
			case auth.UserDoesNotExist:
				text = "用户不存在"
			case PasswordNotInconsistentError:
				text = "用户名或者邮箱不能同时为空"
			default:
				glog.Errorf("%s", err.Error())
				text = "未知错误请联系管理员查证"
			}
			o.ErrorResponse(errors.New(text))
		} else {
			o.MessageResponse("ok")
		}
	}
}
